package com.weibo.map;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.location.Address;
import android.location.Geocoder;
import android.view.MotionEvent;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.weibo.sina.R;

public class MapOverlay extends Overlay {
	private Context mContext;
	private GeoPoint mGeoPoint;
	public MapOverlay(Context context) {
		super();
		mContext = context;
	}

	@Override
	public boolean onTouchEvent(MotionEvent event, MapView mapView) {
		// ---when user lifts his finger---
		 if (event.getAction() == 1) {                
             GeoPoint p = mapView.getProjection().fromPixels(
                 (int) event.getX(),
                 (int) event.getY());

             Geocoder geoCoder = new Geocoder(
                 mContext, Locale.getDefault());
             try {
                 List<Address> addresses = geoCoder.getFromLocation(
                     p.getLatitudeE6()  / 1E6, 
                     p.getLongitudeE6() / 1E6, 1);

                 String add = "";
                 if (addresses.size() > 0) 
                 {
                     for (int i=0; i<addresses.get(0).getMaxAddressLineIndex(); 
                          i++)
                        add += addresses.get(0).getAddressLine(i) + "\n";
                 }

                 Toast.makeText(mContext, add, Toast.LENGTH_SHORT).show();
             }
             catch (IOException e) {                
                 e.printStackTrace();
             }   
             return true;
         }
         else                
             return false;
	}
	
	 @Override
     public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when)
     {
         super.draw(canvas, mapView, shadow);
         Paint paint = new Paint();
         Point myScreenCoords = new Point();
         // 将经纬度转换成实际屏幕坐标
         mapView.getProjection().toPixels(mGeoPoint, myScreenCoords);
         paint.setStrokeWidth(1);
         paint.setARGB(255, 255, 0, 0);
         paint.setStyle(Paint.Style.STROKE);
         Bitmap bmp = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.ic_location_pin);
         canvas.drawBitmap(bmp, myScreenCoords.x, myScreenCoords.y, paint);
         canvas.drawText("中通福瑞", myScreenCoords.x, myScreenCoords.y, paint);
         return true;
     }

	public GeoPoint getGeoPoint() {
		return mGeoPoint;
	}

	public void setGeoPoint(GeoPoint mGeoPoint) {
		this.mGeoPoint = mGeoPoint;
	}
	 
	 

}
